import {Hono} from 'hono';
import {
    getEastBkzjMix, memorizedEastBKUp,
    memorizedEastMixDown
} from '@/backend/services/east-service';
import {getRankHist, memorizedIgnoredWords} from "@/backend/services/public";
import {cleanName, uniqueSimilarArray} from "@/lib/utils";
import {memoizedKplTopMix} from "@/backend/services/kpl-service";
import {getSecuCurrent} from "@/backend/services/secu-service";
import {eastMixData} from "@/types";


const addLabelToObj = (labels: any, objs: any) => {
    labels.forEach((label: string) => {
        objs.forEach((o: { label: string; f14: string; }) => {

            if (!o.f14.startsWith('#')) {
                if (label.toLowerCase().includes(o.f14.toLowerCase()) || o.f14.toLowerCase().includes(label.toLowerCase())) {
                    o.f14 = `#${o.f14}`
                }
            }
        })
    })
    return objs;
}


export const eastRouter = new Hono()
    .get('/bkzj/mix', async (c) => {
        const ignoredWords: string[] = await memorizedIgnoredWords();
        const eastMix = await getEastBkzjMix();
        const mixData = eastMix?.rank_data as eastMixData[] || [];
        const filtered = mixData.filter(m => !ignoredWords.includes(m.f14))
        const data = uniqueSimilarArray(filtered, 'f14')
        const headerSecuCodes = data.map(d => d.f205)
        const headerSecuCurrent = await getSecuCurrent(headerSecuCodes)
        const objHeadSecus: Record<string, any> = {}
        for (const secu of headerSecuCurrent) {
            objHeadSecus[secu.secu_code] = secu
        }
        // console.log(objSecuCurrent)
        data.map((d: { f62: number, f204: string, f205: string }) => {
            d.f62 = parseFloat((d.f62 / 100000000).toFixed(2));
            const headerCurrent = objHeadSecus[d.f205]
            d.f204 = headerCurrent?.chg >= 5 ? d.f204 : ""
        });
        const ordered = data.sort((a: { f62: number }, b: { f62: number }) => b.f62 - a.f62).slice(0, 5);
        // 共振的添加#号
        const {list: kplMixList} = await memoizedKplTopMix();
        const plateLabels: string[] = kplMixList.map((p: any) => cleanName(p[1]));
        const labeled = addLabelToObj(plateLabels, ordered)
        return c.json({data: labeled});
    })
    .get('/mix/down', async (c) => {
        let rankHist = await getRankHist()
        rankHist = rankHist.map(r => cleanName(r))
        rankHist = rankHist.filter(r => r !== '')
        const cached = await memorizedEastMixDown()
        let downList = structuredClone(cached)
        // console.log(downList)
        // labeled
        downList = downList.map(d => {
            d.label = d.f14.split('ETF').at(0) || ''
            for (const plate of rankHist) {
                if (d.label.toUpperCase().includes(plate.toUpperCase()) || plate.toUpperCase().includes(d.label.toUpperCase())) {
                    d.label = plate
                }
            }
            d.label = d.label.toUpperCase();
            return d
        })
        // 存在hist且 chg<0
        downList = downList.filter((d: { f14: string; f3: number; label: string; }) => {
            const upperHist = rankHist.map(r => r.toUpperCase())
            return upperHist.includes(d.label) && d.f3 < 0 && d.f14 !== '';
        })
        downList = downList.filter((v: any, index: any, selfArr: any) => index === selfArr.findIndex((t: any) => t.label === v.label))
        return c.json({data: downList})
    }).get('/bk/mix/up', async (c) => {
        const ignoredWords: string[] = await memorizedIgnoredWords();
        const cached = await memorizedEastBKUp()
        let upList = structuredClone(cached)
        // upList = upList.map(u=>)
        upList = upList.filter(u => !u.f14.startsWith('昨') && !ignoredWords.includes(u.f14))
        upList = upList.sort((a, b) => b.f3 - a.f3)
        // 共振的添加#号
        const {list: kplMixList} = await memoizedKplTopMix();
        const plateLabels: string[] = kplMixList.map((p: any) => cleanName(p[1]));
        const labeled = addLabelToObj(plateLabels, upList)
        return c.json({data: labeled})
    })


// .get('/bkzj/gn', async (c) => {
//     const data = await memorizedBkzjGn();
//     data.map((d: { f62: number }) => {
//         d.f62 = parseFloat((d.f62 / 100000000).toFixed(2));
//     });
//     // const filteredData = data.filter((d: { f13: number; }) => d.f13 === 90)
//     // const orderedData = filteredData.sort((a: { f62: number; }, b: { f62: number; }) => b.f62 - a.f62);
//     return c.json({data: data});
// })
//     .get('/bk/mix', async (c) => {
//         const dataGnList = await fetchBkGn();
//         const dataHyList = await fetchBkHy();
//         const data = [...dataGnList.filter((d: { f14: string }) => !d.f14.startsWith('昨')), ...dataHyList];
//         const ordered = data.sort((a: { f3: number }, b: { f3: number }) => b.f3 - a.f3).slice(0, 5);
//         return c.json({data: ordered});
//     })
//     .get('/bk/gn', async (c) => {
//         const data = await fetchBkGn();
//         const filtered = data.filter((d: { f14: string }) => !d.f14.startsWith('昨'));
//         return c.json({data: filtered});
//     })
//     .get('/hk/up', async (c) => {
//         const data = await fetchHKStock();
//         const handledData = data.map((d: { f3: number }) => {
//             d.f3 = parseFloat((d.f3 / 100).toFixed(2));
//             return d;
//         });
//         const ordered = handledData.sort((a: { f3: number }, b: { f3: number }) => b.f3 - a.f3).slice(0, 5);
//         const filtered = ordered.filter((d: { f3: number }) => d.f3 > 20);
//         return c.json({data: filtered});
//     })
//     .get('/hk/index/up', async (c) => {
//         const data = await fetchHKIndex();
//         const handledData = data.map((d: { f3: number }) => {
//             d.f3 = parseFloat((d.f3 / 100).toFixed(2));
//             return d;
//         });
//         const ordered = handledData.sort((a: { f3: number }, b: { f3: number }) => b.f3 - a.f3).slice(0, 5);
//         const filtered = ordered.filter((d: { f3: number }) => d.f3 > 20);
//         return c.json({data: filtered});
//     })